package com.hlk.admin.service.impl;

import com.github.pagehelper.PageHelper;
import com.hlk.admin.mapper.AdminUserMapper;
import com.hlk.admin.service.AdminUserService;
import com.hlk.enums.ResponseStatusEnum;
import com.hlk.exception.HuaException;
import com.hlk.pojo.AdminUser;
import com.hlk.pojo.bo.NewAdminBO;
import com.hlk.utils.ConvertUtils;
import com.hlk.utils.PageResult;
import com.hlk.utils.PageUtils;
import org.apache.commons.lang3.StringUtils;
import org.n3r.idworker.Sid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.entity.Example;

import java.util.Date;
import java.util.List;

/**
 * @author hlk
 * @version 1.0
 * @date 2020-12-23 8:50
 */
@Service
public class AdminUserServiceImpl implements AdminUserService {
    @Autowired
    private Sid sid;
    @Autowired
    private AdminUserMapper adminUserMapper;

    @Override
    public AdminUser selectByUsername(String username) {
        Example example = new Example(AdminUser.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("username", username);

        return adminUserMapper.selectOneByExample(example);
    }

    @Override
    public void insertNewAdmin(NewAdminBO newAdminBO) {
        AdminUser adminUser = ConvertUtils.sourceToTarget(newAdminBO, AdminUser.class);
        adminUser.setId(sid.nextShort());

        if (StringUtils.isNotBlank(newAdminBO.getPassword())) {
            adminUser.setPassword(newAdminBO.getPassword());
        }
        if (StringUtils.isNotBlank(newAdminBO.getFaceId())) {
            adminUser.setFaceId(newAdminBO.getFaceId());
        }

        adminUser.setCreatedTime(new Date());
        adminUser.setUpdatedTime(new Date());

        int insert = adminUserMapper.insert(adminUser);
        if (insert != 1) {
            throw new HuaException(ResponseStatusEnum.ADMIN_CREATE_ERROR);
        }
    }

    @Override
    public PageResult selectAdminUserByPage(Integer page, Integer pageSize) {
        Example example = new Example(AdminUser.class);
        example.orderBy("createdTime").desc();

        PageHelper.startPage(page, pageSize);
        List<AdminUser> list = adminUserMapper.selectByExample(example);

        PageResult pageResult = PageUtils.getResult(page, list);

        return pageResult;
    }

}
